﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utils
{
    public class SerialPortHelp
    {
        #region 变量属性

        public event Action<List<byte>> DataReceived;
        public event SerialErrorReceivedEventHandler ErrorReceived;

        private SerialPort serialPort = new SerialPort();
        private string portName { get; set; } = "COM3";//串口号，默认COM1
        private BaudRates baudRate { get; set; } = BaudRates.BR_38400;//波特率
        private Parity parity { get; set; } = Parity.None;//校验位
        private StopBits stopBits { get; set; } = StopBits.One;//停止位
        private DataBits dataBits { get; set; } = DataBits.Eight;//数据位
                                                           
        /// <summary>
        /// 数据仓库
        /// </summary>
        List<byte> datapool = new List<byte>();//存放接收的所有字节

        #endregion

        public SerialPortHelp()
        {
            BoundEvents();
        }

        /// <summary>
        /// 参数构造函数（使用枚举参数构造）
        /// </summary>
        /// <param name="baud">波特率</param>
        /// <param name="par">奇偶校验位</param>
        /// <param name="sBits">停止位</param>
        /// <param name="dBits">数据位</param>
        /// <param name="name">串口号</param>
        public SerialPortHelp(string name, BaudRates baud, Parity par, DataBits dBits, StopBits sBits)
        {
            portName = string.IsNullOrEmpty(name)? portName:name;
            baudRate = baud;
            parity = par;
            dataBits = dBits;
            stopBits = sBits;
            BoundEvents();
        }


        private void BoundEvents()
        {
            serialPort.DataReceived+=new SerialDataReceivedEventHandler(SerialPort_DataReceived);
            serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(SerialPort_ErrorReceived);
        }

        #region 事件处理函数
        /// <summary>
        /// 数据接收处理
        /// </summary>
       private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort.IsOpen)     //判断是否打开串口
            {

                Byte[] receivedData = new Byte[serialPort.BytesToRead];        //创建接收字节数组
                serialPort.Read(receivedData, 0, receivedData.Length);         //读取数据

                //触发整条记录的处理
                if (DataReceived != null)
                {
                    //datapool = new List<byte>();
                    datapool.AddRange(receivedData);
                    DataReceived(datapool);
                }

            }
            else
            {
                Console.WriteLine("请打开某个串口", "Error");
            }
        }

        /// <summary>
        /// 错误处理函数
        /// </summary>
       private void SerialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {
            if (ErrorReceived != null)
            {
                ErrorReceived(sender, e);
            }
        }

        #endregion

        #region 串口关闭/打开
        /// <summary>
        /// 端口是否已经打开
        /// </summary>
        public bool IsOpen
        {
            get
            {
                return serialPort.IsOpen;
            }
        }

        /// <summary>
        /// 打开端口
        /// </summary>
        /// <returns></returns>
        public void Open()
        {
            if (serialPort.IsOpen)
                serialPort.Close();

            serialPort.PortName = portName;
            serialPort.BaudRate = (int)baudRate;
            serialPort.Parity = parity;
            serialPort.DataBits = (int)dataBits;
            serialPort.StopBits = stopBits;

            //serialPort.Open();
        }

        /// <summary>
        /// 关闭端口
        /// </summary>
        public void Close()
        {
            if (serialPort.IsOpen)
                serialPort.Close();
        }

        /// <summary>
        /// 丢弃来自串行驱动程序的接收和发送缓冲区的数据
        /// </summary>
        public void DiscardBuffer()
        {
            serialPort.DiscardInBuffer();
            serialPort.DiscardOutBuffer();
        }
        #endregion

        #region 写入数据
        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="buffer"></param>
        public void Write(byte[] buffer, int offset, int count)
        {
            if (!serialPort.IsOpen)
                serialPort.Open();
            serialPort.Write(buffer, offset, count);
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="buffer">写入端口的字节数组</param>
        public void Write(byte[] buffer)
        {
            if (!(serialPort.IsOpen))
                serialPort.Open();
            serialPort.Write(buffer, 0, buffer.Length);
        }
        #endregion
    }

    #region 波特率、数据位的枚举
    /// <summary>
    /// 串口数据位列表（5,6,7,8）
    /// </summary>
    public enum DataBits : int
    {
        Five = 5,
        Six = 6,
        Sevent = 7,
        Eight = 8
    }

    /// <summary>
    /// 串口波特率列表。
    /// 75,110,150,300,600,1200,2400,4800,9600,14400,19200,28800,38400,56000,57600,
    /// 115200,128000,230400,256000
    /// </summary>
    public enum BaudRates : int
    {
        BR_75 = 75,
        BR_110 = 110,
        BR_150 = 150,
        BR_300 = 300,
        BR_600 = 600,
        BR_1200 = 1200,
        BR_2400 = 2400,
        BR_4800 = 4800,
        BR_9600 = 9600,
        BR_14400 = 14400,
        BR_19200 = 19200,
        BR_28800 = 28800,
        BR_38400 = 38400,
        BR_56000 = 56000,
        BR_57600 = 57600,
        BR_115200 = 115200,
        BR_128000 = 128000,
        BR_230400 = 230400,
        BR_256000 = 256000
    }
    #endregion
}
